package com.bw.unit3.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.bw.unit3.base.BaseBean
import com.bw.unit3.base.BaseViewModel
import com.bw.unit3.bean.LoginBean
import com.bw.unit3.bean.LoginResult
import com.bw.unit3.http.HttpUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *
 * @ClassName: LoginViewModel
 * @Description: java类作用描述
 * @Author: zhangyanchao
 * @CreateDate: 2024/9/13 11:27 AM
 * @Version: 1.0
 */
class LoginViewModel : BaseViewModel() {

    val loginLiveData = MutableLiveData<BaseBean<LoginBean>>()

    //使用密封类，传递登录结果
    val loginLiveResult = MutableLiveData<LoginResult>()
    fun login(map: Map<String, String>) {
        //创建协程
        viewModelScope.launch(Dispatchers.IO) {
            //发起请求，显示loading
            loginLiveResult.postValue(LoginResult.Start())

            delay(500)

            //调用接口，实现登录
            val res = HttpUtil.apiService.loginjson(map)
            if (res.code != 200) {
                loginLiveResult.postValue(LoginResult.Failed(res.code))
            } else {
                loginLiveResult.postValue(LoginResult.Success(res.data))
            }
//            loginLiveData.postValue(HttpUtil.apiService.loginjson(map))
        }
    }

    //使用flow 更新请求结果
    val loginFlowData = MutableSharedFlow<BaseBean<LoginBean>>()
    fun loginFlow(map: Map<String, String>) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                loginFlowData.emit(HttpUtil.apiService.loginjson(map))
                //背压处理
                loginFlowData.buffer()
            }
        }
    }
}

